//
//  ConversationListViewController.m
//  TIMChat
//
//  Created by wilderliao on 16/2/16.
//  Copyright © 2016年 AlexiChen. All rights reserved.
//

#import "ConversationListViewController.h"
#import "IMAChatViewController.h"
#import "ConversationListTableViewCell.h"
#import "SpecialConversationListTableViewCell.h"
#import <UIImage+Resize.h>
#import "UserInfoModel.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import "XLHTTPSessionManager+Analytics.h"
#import "XLTalkedPeopleViewController.h"
#import <MJRefresh.h>
#import "XLTabBarController.h"
#import "XLHTTPSessionManager+matchOrder.h"
#import "XLOrderViewController.h"
#import "XLNewOrderViewController.h"
#import "XLSearchViewController.h"
#import "NSObject+FBKVOController.h"


@interface ConversationListViewController (){

    NSInteger _index;
}

@property (nonatomic,strong) UIScrollView     *emptyScrollView;
@property (nonatomic,strong) UIImageView      *imageView;
@property (nonatomic,strong) UILabel          *titleLabel;
@property (nonatomic,strong) UILabel          *secondtitleLabel;
@property (nonatomic,strong) UIButton         *loginButton;
@property (nonnull, strong) UIButton          *unReadBadge;;

@property (nonatomic,strong) UIImageView      *commentView;
@property (nonatomic,strong) UIImageView      *likeView;
@property (nonatomic,strong) UIImageView      *girlView;
@property (nonatomic,strong) UIImageView      *spchatView;
@property (nonatomic,strong) IMAMsg           *lastMessage;

@property (nonatomic,strong)UIView            *beautyTopView;
@property (nonatomic,strong)UIImageView       *videochatTopImg;
@property (nonatomic,strong)UILabel           *redPoint;
@property (nonatomic,strong)NSMutableArray    *orderListAry;
@property (nonatomic,assign)NSInteger          orderInter;
@property (nonatomic,assign)BOOL               isAppear;

@end

@implementation ConversationListViewController


- (void)addHeaderView{}

- (void)addFooterView {}

- (BOOL)hasData
{
    BOOL has = _conversationList.count != 0;
    return has;
}

- (void)addRefreshScrollView
{
    _tableView = [[UITableView alloc] init];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.scrollsToTop = YES;
    [self.view addSubview:_tableView];

    _tableView.separatorInset = UIEdgeInsetsMake(8, 0, 0, 0);
    self.refreshScrollView = _tableView;
    
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    [self analyticsEvent1];
    [self setUI];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:@"loginSuccess" object:nil];
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"repeatSelectMessage" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self.tableView.mj_header beginRefreshing];
    }];
    [self addObserver];
    
}

-(void)setUI
{
    self.navigationItem.title = @"消息";
    
    self.view.backgroundColor = RGB_HEX(0xF9F9F9);
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor blackColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.tabBarController.tabBar.translucent = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self pinHeaderView];
    
    //删除会话
    UIButton * deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 24, 24)];
    [deleteBtn setImage:IMAGE_NAMED(@"delete_new") forState:UIControlStateNormal];
    [deleteBtn setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [deleteBtn setContentEdgeInsets:UIEdgeInsetsMake(0, 16, 0, -16)];
    deleteBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
    kWeakSelf(self);
    [deleteBtn addTapBlock:^(UIButton *btn) {
        UIAlertController * alter = [UIAlertController alertControllerWithTitle:@"删除所有聊天记录，一经操作，您的聊天记录都会被删除" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            for(int i = 0; i < [_conversationList count]; i++)
            {
                if(i != 0)
                {
                    IMAConversation *userconv = [_conversationList objectAtIndex:i];
                    if([[TIMManager sharedInstance] deleteConversationAndMessages:[userconv type] receiver:[userconv receiver]])
                    {
                        NSLog(@"删除成功");
                    }else
                    {
                        NSLog(@"删除失败");
                    }
                }
            }
            NSInteger count = [_conversationList count] - 1;
            for(int i = 0; i < count; i++)
            {
                [_conversationList removeLastObject];
            }
            [weakself reloadData];
        }];
        UIAlertAction * canel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alter addAction:sure];
        [alter addAction:canel];
        [weakself presentViewController:alter animated:YES completion:nil];
        
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:deleteBtn];
}

- (void)addObserver {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"OrderRefresh" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
        {
            if (self.isAppear) {
                [self userOderListData];
            }
        }
    }];
}


- (void)updateCellOnline
{
    NSInteger readCount = self.orderInter;
    if ( readCount <= 9 &&  readCount > 0)
    {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(20, 16));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }else if (readCount >= 10) {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 20));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }else {
        _redPoint.hidden = YES;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(0, 0));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
        
    }
    [_redPoint setText:readCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld",readCount]];
}

-(void)hostTapGestureRecognizer:(UIView *)view
{
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(hostTapAction:)];
    [view addGestureRecognizer:tap];
}

#pragma mark -
#pragma mark -主播-抢单大厅
-(void)hostTapAction:(UITapGestureRecognizer *)tap
{
    //主播-抢单大厅
    NSLog(@"主播-抢单大厅");
    if ([self checkCameraAuthorization]) {
        XLNewOrderViewController *vc = [[XLNewOrderViewController alloc] init];
        vc.view.backgroundColor=[UIColor colorWithWhite:0 alpha:0.77];
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:vc animated:YES completion:^(void){
            vc.view.superview.backgroundColor = [UIColor clearColor];
        }];
    }
}

-(void)userOderListData
{
    [[[XLHTTPSessionManager sharedManager] getOrderListWithAnchorId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSLog(@"订单列表数据==%@",x);
        self.orderListAry = x;
        if (self.orderListAry.count > 0 || self.orderListAry.count == 0) {
            self.orderInter = self.orderListAry.count;
            [self updateCellOnline];
        }
        
    } error:^(NSError *error) {
        
    }];
}

#pragma mark -

- (void)headerRefresh {
    [self.tableView.mj_header endRefreshing];
    IMAConversationManager *mgr = [IMAPlatformxl sharedInstance].conversationMgr;
    [mgr asyncUpdateUnReadmessageNumb];
    [mgr chatWith:@"10000"];
    IMAUser *user = [[IMAUser alloc] initWith:@"10000"];
    [mgr msgchatWith:user];
    [mgr asyncUpdateConversationList];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10000"];
    IMAConversation *conv = [[IMAConversation alloc]initWith:con];
    if (![mgr.conversationList containsObject:conv]) {
        [mgr.conversationList insertObject:conv atIndex:0];
    }else{
        [mgr.conversationList removeObject:conv];
        [mgr.conversationList insertObject:conv atIndex:0];
    }
    _conversationList = [mgr conversationList];
    [self.tableView reloadData];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
    //return UIStatusBarStyleDefault;
}

//创建聊天室
- (void)addNewgroupNavAction {

}

- (void)layoutSubviewsFrame {
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)loginSuccess:(NSNotification *)notification {
    
    IMAConversationManager *mgr = [IMAPlatformxl sharedInstance].conversationMgr;
    [mgr asyncUpdateUnReadmessageNumb];
    [mgr chatWith:@"10000"];
    IMAUser *user = [[IMAUser alloc] initWith:@"10000"];
    [mgr msgchatWith:user];
    [mgr asyncUpdateConversationList];
    _conversationList = [mgr conversationList];
    __weak ConversationListViewController *ws = self;
    mgr.conversationChangedCompletion = ^(IMAConversationChangedNotifyItem *item) {
        [ws onConversationChanged:item];
    };
    self.KVOController = [FBKVOController controllerWithObserver:self];
    [self.tableView reloadData];

}

- (void)showBackButton:(void (^)(void))clickBlock{
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
    
    UIImage *backImg = [UIImage imageNamed:@"common_nav_btn_back_n"];
    backImg = [backImg imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [backButton setImage:backImg forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
    
    @weakify(self);
    [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        if (clickBlock) {
            clickBlock();
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [[IMAPlatformxl sharedInstance].conversationMgr releaseChattingConversation];
    [HelpTool statStartEventId:@"105" eventLabel:@"进入私聊列表页"];
}

- (void)removePromptView {

}

- (void)addSearchController
{
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    XLTabBarController *tabVC = (XLTabBarController *)self.tabBarController;
//    [tabVC.launchAnimation play];
    [UserDefaults setObject:@"3" forKey:@"tabBarSelectedIndex"];
    [UserDefaults synchronize];
    self.isAppear = YES;
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        //[self userOderListData];
    }
    [self configOwnViews];
    IMAConversationManager *mgr = [IMAPlatformxl sharedInstance].conversationMgr;
    [mgr asyncUpdateUnReadmessageNumb];


    TIMConversation     *conversation;
    conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10001"];
    NSArray *meaage = [conversation getLastMsgs:1];
    for (TIMMessage *msg in meaage)
    {
        //        if (msg.status != TIM_MSG_STATUS_HAS_DELETED)
        //        {
        IMAMsg *imamsg = [IMAMsg msgWith:msg];
        self.lastMessage = imamsg;
        _index =   [conversation getUnReadMessageNum];
        [_tableView reloadData];
        
    }
    [mgr chatWith:@"10000"];
    IMAUser *user = [[IMAUser alloc] initWith:@"10000"];
    [mgr msgchatWith:user];
    [mgr asyncUpdateConversationList];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10000"];
    IMAConversation *conv = [[IMAConversation alloc]initWith:con];
    if (![mgr.conversationList containsObject:conv]) {
        [mgr.conversationList insertObject:conv atIndex:0];
    }else{
        [mgr.conversationList removeObject:conv];
        [mgr.conversationList insertObject:conv atIndex:0];
    }
    _conversationList = [mgr conversationList];
    [self.tableView reloadData];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pingkuntongzhi:) name:@"pingkuntongzhi" object:nil];
    

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isAppear = NO;
}

- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}


- (void)pingkuntongzhi:(NSNotificationCenter *)sender {
    TIMConversation     *conversation;
    conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10001"];
    NSArray *meaage = [conversation getLastMsgs:1];
    for (TIMMessage *msg in meaage)
    {
        //        if (msg.status != TIM_MSG_STATUS_HAS_DELETED)
        //        {
        IMAMsg *imamsg = [IMAMsg msgWith:msg];
        self.lastMessage = imamsg;
        _index =   [conversation getUnReadMessageNum];
        [_tableView reloadData];

    }
}

- (void)configOwnViews
{
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
//        return;
//    }
    IMAConversationManager * mgr = [IMAPlatformxl sharedInstance].conversationMgr;
    [mgr asyncUpdateUnReadmessageNumb];
    [mgr chatWith:@"10000"];
    IMAUser *user = [[IMAUser alloc] initWith:@"10000"];
    [mgr msgchatWith:user];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10000"];
    IMAConversation *conv = [[IMAConversation alloc]initWith:con];
    if (![mgr.conversationList containsObject:conv]) {
        [mgr.conversationList insertObject:conv atIndex:0];
    }else{
        [mgr.conversationList removeObject:conv];
        [mgr.conversationList insertObject:conv atIndex:0];
    }
    _conversationList = [mgr conversationList];

    __weak ConversationListViewController *ws = self;
    mgr.conversationChangedCompletion = ^(IMAConversationChangedNotifyItem *item) {
//        if ([[UserDefaults objectForKey:BMHIsLogined] boolValue] == NO) {
//        }else {
            [ws onConversationChanged:item];

//        }
    };
    
    [self.tableView reloadData];
    
    self.KVOController = [FBKVOController controllerWithObserver:self];
    [self.KVOController observe:[IMAPlatformxl sharedInstance].conversationMgr keyPath:@"unReadMessageCount" options:NSKeyValueObservingOptionNew block:^(id observer, id object, NSDictionary *change) {
        [ws onUnReadMessag];
    }];
    [ws onUnReadMessag];
}

- (void)onUnReadMessag
{

}


- (void)onConversationChanged:(IMAConversationChangedNotifyItem *)item
{
    
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
//        return;
//    }
    switch (item.type)
    {
        case EIMAConversation_SyncLocalConversation:
        {
            [self reloadData];
        }
            
            break;
        case EIMAConversation_BecomeActiveTop:
        {
//            [self.tableView beginUpdates];//老会话插入的位置
//            [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:item.index inSection:1] toIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
//            [self.tableView endUpdates];
//            更新一下本地消息数据
            IMAConversationManager *mgr = [IMAPlatformxl sharedInstance].conversationMgr;
            [mgr asyncUpdateUnReadmessageNumb];
            [mgr chatWith:@"10000"];
            IMAUser *user = [[IMAUser alloc] initWith:@"10000"];
            [mgr msgchatWith:user];
            [mgr asyncUpdateConversationList];
            TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10000"];
            IMAConversation *conv = [[IMAConversation alloc]initWith:con];
            if (![mgr.conversationList containsObject:conv]) {
                [mgr.conversationList insertObject:conv atIndex:0];
            }else{
                [mgr.conversationList removeObject:conv];
                [mgr.conversationList insertObject:conv atIndex:0];
            }
            _conversationList = [mgr conversationList];
            [_tableView reloadData];
        }
            break;
        case EIMAConversation_NewConversation:
        {
//            [self.tableView beginUpdates];//新会话
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:1];
            if (_conversationList.count > 0) {
                index = [NSIndexPath indexPathForRow:1 inSection:1];
            }
            [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
//            [self.tableView endUpdates];
            IMAConversationManager *mgr = [IMAPlatformxl sharedInstance].conversationMgr;
            [mgr asyncUpdateUnReadmessageNumb];
            [mgr chatWith:@"10000"];
            IMAUser *user = [[IMAUser alloc] initWith:@"10000"];
            [mgr msgchatWith:user];
            [mgr asyncUpdateConversationList];
            TIMConversation *con = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:@"10000"];
            IMAConversation *conv = [[IMAConversation alloc]initWith:con];
            if (![mgr.conversationList containsObject:conv]) {
                [mgr.conversationList insertObject:conv atIndex:0];
            }else{
                [mgr.conversationList removeObject:conv];
                [mgr.conversationList insertObject:conv atIndex:0];
            }
            _conversationList = [mgr conversationList];
            [self.tableView reloadData];//临时处理方案
        }
            break;
        case EIMAConversation_DeleteConversation:
        {
            [self.tableView reloadData];

        }
            break;
        case EIMAConversation_Connected:
        {
//            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:1];
            [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
//            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_DisConnected:
        {
//            [self.tableView beginUpdates];
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:1];
            [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
//            [self.tableView endUpdates];
        }
            break;
        case EIMAConversation_ConversationChanged:
        {
//            [self.tableView beginUpdates];//刷新已有会话
            NSIndexPath *index = [NSIndexPath indexPathForRow:item.index inSection:1];
            [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
            
//            [self.tableView endUpdates];
        }
            break;
        default:
            
            break;
    }
    
}
- (void)onRefresh
{

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        return 1;
    }
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
        return [conv showHeight];
    }
    if (indexPath.section == 0) {
        return 65;

    }else {
        id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
        return [conv showHeight];

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        return _conversationList.count;
    }
    if (section == 0 ) {

        return 1;
        
    }else {

        return  _conversationList.count;

    }
}

- (void)extracted:(ConversationListTableViewCell *)cell conv:(id<IMAConversationShowAble>)conv user:(IMAUser *)user {

          [cell configCellWith:conv withUser:user];
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
        
        NSString *reuseidentifier = [conv showReuseIndentifier];
        [conv attributedDraft];
        id<IMAConversationShowAble> tempCon = [[[IMAPlatformxl sharedInstance].conversationMgr conversationList] objectAtIndex:indexPath.row];
        [tempCon attributedDraft];
        IMAConversation *userconv = conv;
        ConversationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseidentifier];
        if (!cell)
        {
            cell = [[ConversationListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseidentifier];
            cell.selectedBackgroundView = [[UIView alloc] init];
            cell.selectedBackgroundView.backgroundColor = kLightGrayColor;
        }
        cell.backgroundColor = KClearColor;
        IMAUser *user = [[IMAUser alloc] initWith:[userconv receiver]];
        
        [self extracted:cell conv:conv user:user];
        
        return cell;
    }
    if (indexPath.section == 0) {
        NSString *reuseidentifier =@"IMAConnectConversation_ReuseInd";
        NSArray  *imageArr;
        NSArray  *titleArr;
        NSArray  *numberArr;
        titleArr  = [NSArray arrayWithObjects:@"聊过的人", nil];
        numberArr = [NSArray arrayWithObjects:@(0), nil];
        imageArr  = [NSArray arrayWithObjects:@"message_list_icon_liaoguo_n",nil];
        SpecialConversationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseidentifier];
        
        if (!cell)
        {
            cell = [[SpecialConversationListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseidentifier];
            cell.selectedBackgroundView = [[UIView alloc] init];
            cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
        }
        [tableView setSeparatorColor:RGB_HEX(0xeeeeee)];
        [cell setHeadImageStr:imageArr[indexPath.row] withName:titleArr[indexPath.row] withMessageNmber:[numberArr[indexPath.row] integerValue] withlastmessge:_lastMessage];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = RGB_HEX(0xffffff);

        return cell;
    } else {
        id<IMAConversationShowAble> conv = [_conversationList objectAtIndex:indexPath.row];
        
        NSString *reuseidentifier = [conv showReuseIndentifier];
        [conv attributedDraft];
        id<IMAConversationShowAble> tempCon = [[[IMAPlatformxl sharedInstance].conversationMgr conversationList] objectAtIndex:indexPath.row];
        [tempCon attributedDraft];
        IMAConversation *userconv = conv;
        ConversationListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseidentifier];
        if (!cell)
        {
            cell = [[ConversationListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseidentifier];
            cell.selectedBackgroundView = [[UIView alloc] init];
            cell.selectedBackgroundView.backgroundColor = kLightGrayColor;
        }
        [tableView setSeparatorColor:RGB_HEX(0xEEEEEE)];
        cell.backgroundColor = RGB_HEX(0xffffff);
        IMAUser *user = [[IMAUser alloc] initWith:[userconv receiver]];
        
        [self extracted:cell conv:conv user:user];

        return cell;

    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//不
        if (indexPath.row == 0) {
            return NO;
        }
        return YES;
    }
    if (indexPath.section == 0) {
        return NO;
    }else {
        if (indexPath.row == 0) {
            return NO;
        }
        return YES;
    }
}

//标记 删除
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || (indexPath.section > 0 && indexPath.row == 0)) {
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//不
            return nil;
        }
        
    }
    
    //判断是否需要出现 ‘取消标记’ 按钮
    
    //1.获取对应的cell
    ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    //标记是否有未读消息
    BOOL isUnReadCount = NO;
    
    if (cell) {
        
        //获取是否有未读消息
        NSInteger unReadCount = [cell getUnReadCount];
        
        if (unReadCount > 0) {
            
            isUnReadCount = YES;
            
        }else{
            isUnReadCount = NO;
        }
        
    }
    
    //2.根据未读消息的存在显示事件
    
    UITableViewRowAction *markAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDestructive) title:@"标记已读" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        //取消标记事件
        if (isUnReadCount) {
            
            //标记读取信息
            [cell markReaded];
        }
        
    }];
    
    markAction.backgroundColor = [UIColor grayColor];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDestructive) title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        //删除事件
        if (indexPath.row > 0) {
            IMAConversation *conv = [self->_conversationList objectAtIndex:indexPath.row];
            [[IMAPlatformxl sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
        }
        
    }];
    
    //3.区别读取和为读取信息状态
    if (isUnReadCount) {
        return @[deleteAction,markAction];
    }else{
        return @[deleteAction];
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 || (indexPath.section > 0 && indexPath.row == 0)) {
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//不
            return;
        }
    }
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:(UITableViewRowAnimationTop)];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [self skipchatView:indexPath View:tableView];
        return;
    }
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            XLTalkedPeopleViewController * talkedVC = [[XLTalkedPeopleViewController alloc] init];
            [self.navigationController pushViewController:talkedVC animated:YES];
            
        }
    }else{
        [self skipchatView:indexPath View:tableView];
    }
}

#pragma mark ---跳转聊天界面
-(void)skipchatView:(NSIndexPath *)indexPath View:(UITableView *)tableView
{
    id<IMAConversationShowAble> convable = [_conversationList objectAtIndex:indexPath.row];
    ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    IMAConversation *conv = (IMAConversation *)convable;
    IMAConversation *userconv = conv;
    
    switch ([convable conversationType])
    {
        case IMA_C2C:
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[[userconv receiver]] succ:^(NSArray *friends) {
                    for (TIMUserProfile *pro in friends)
                    {
                        IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                        NSLog(@"gbnnnnn == %@", user.nickName);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                            [self.navigationController pushViewController:chat animated:YES ];
                            [conv setReadAllMsg];
                            ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                            [cell refreshCell];
                            [HelpTool statStartEventId:@"10501" eventLabel:@"从私聊列表进私聊"];
                        });
                        
                        
                        
                        
                    }
                } fail:^(int code, NSString *msg) {
                    DebugLog(@"Failddd: %d->%@", code, msg);
                }];
                
            });
            
        }
            break;
        case IMA_Group:
        {
            IMAUser *user = [[IMAPlatformxl sharedInstance] getReceiverOf:conv];
            
            if (user){
                //                [[AppDelegate sharedAppDelegate] pushToChatViewControllerWith:user];
                
                
                NSLog(@"ggnnnnnnnnnnn == %@", user.userId);
                
                IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                
                chat.hidesBottomBarWhenPushed = YES;
                
                [self.navigationController pushViewController:chat animated:YES ];
                [conv setReadAllMsg];
                
                [cell refreshCell];
                chat.ChatViewBackBlock = ^{
                    [cell refreshCell];
                    [conv setReadAllMsg];
                    
                };
                
            }
            else
            {
                if ([conv type] == TIM_C2C)
                {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[[userconv receiver]] succ:^(NSArray *friends) {
                            for (TIMUserProfile *pro in friends)
                            {
                                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                                NSLog(@"gbnnnnn == %@", user.nickName);
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                                    //                                [chat configWithUser:user];
                                    //                                    [[IMAPlatformxl sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
                                    
                                    chat.hidesBottomBarWhenPushed = YES;
                                    
                                    [self.navigationController pushViewController:chat animated:YES ];
                                    
                                    [conv setReadAllMsg];
                                    ConversationListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                                    [cell refreshCell];
                                    [HelpTool statStartEventId:@"10501" eventLabel:@"从私聊列表进私聊"];
                                    chat.ChatViewBackBlock = ^{
                                        [cell refreshCell];
                                        [conv setReadAllMsg];
                                        
                                    };
                                });
                                
                                
                                
                                
                            }
                        } fail:^(int code, NSString *msg) {
                            DebugLog(@"Failddd: %d->%@", code, msg);
                        }];
                        
                    });
                    
                    
                }
                else if ([conv type] == TIM_GROUP)
                {
                    //                            [[IMAPlatformxl sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
                    
                    // 有可能是因为退群本地信息信息未同步
                    [[IMAPlatformxl sharedInstance].conversationMgr deleteConversation:conv needUIRefresh:YES];
                }
                
            }
        }
            break;
            
        case IMA_Sys_NewFriend:
        {
            [conv setReadAllMsg];
            [cell refreshCell];
            [IMAPlatformxl sharedInstance].contactMgr.hasNewDependency = NO;
            
            //            FutureFriendsViewController *vc = [[FutureFriendsViewController alloc] init:YES];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc];
        }
            break;
            
        case IMA_Sys_GroupTip:
        {
            [conv setReadAllMsg];
            [cell refreshCell];
            [IMAPlatformxl sharedInstance].contactMgr.hasNewDependency = NO;
            //            GroupSystemMsgViewController *vc = [[GroupSystemMsgViewController alloc] init];
            //            [[AppDelegate sharedAppDelegate] pushViewController:vc];
        }
            break;
            
        case IMA_Connect:
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

            return 0;

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {

            return 3;

    }else
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *headView;

    headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    headView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    
    return headView;
}

- (void)ChatFaceSelectBtn:(UIButton *)btn andSelectID:(NSString *)SelectID {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
    NSString * useridStr   = SelectID;
    NSString * boundSource = @"4";
    //时间
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@",objIDUser,useridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"Type",useridStr,@"Userid",boundSource,@"Boundsource",locationString,@"Timestamp",natUser,@"Appsign",nil];
    
    [BMHHTTPSession GET:@"/MobileInterface/User/UserInfo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        
        NSLog(@"=====dd个人资料json====%@",JSON);
        [self getSelectChatIdDic:JSON[@"result"][@"data"]];
    } failure:^(NSError * _Nullable error) {
        
    }];
    
}

- (void)getSelectChatIdDic:(NSDictionary *)faceDic {
    
    
    UserInfoModel *faceuserInfoModel = [[UserInfoModel alloc] initWithDic:faceDic];
    // 隐藏键盘，只能选择图片或视频文件
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
    NSString *peeridStr = [NSString stringWithFormat:@"%@",faceuserInfoModel.Id];
    
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    
    NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"Type",uid,@"Userid",peeridStr,@"Anchorid", @"2",@"Rtype",locationString,@"Timestamp",natUser,@"Appsign",nil];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
        NSString * errcode  = JSON[@"result"][@"errcode"];

        if ([errcode isEqualToString:@"0"])
        {
            NSString * callID =  [NSString stringWithFormat:@"%@",JSON[@"result"][@"data"][@"CallID"]];

//            NSUser_save(videoID,kVideoID);//创建通话ID
//            NSUser_save(callID,ChatToChatCallId);//创建通话ID
            
        }else if ([errcode isEqualToString:@"-2"])
        {
            [HelpTool startTipViewWithText:@"你的账号余额不足，请充值！" duration:2.0f type:kTipViewTypeNone];
            
        }else if ([errcode isEqualToString:@"-10"])
        {
            [HelpTool startTipViewWithText:@"您的通话发起失败,请重新发起!" duration:2.0f type:kTipViewTypeNone];
            
        }else if ([errcode isEqualToString:@"-3"])
        {
            [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:peeridStr];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
                
            }];
            
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"===创建通话====%@",JSON);
    } failure:^(NSError * _Nullable error) {
        NSLog(@"===创建通话失败===%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
    
    
}

- (void)handleCommentview:(UITapGestureRecognizer *)sender {
    
  
}

- (void)handleLikeTapview:(UITapGestureRecognizer *)sender {
    


}

- (void)handleGifview:(UITapGestureRecognizer *)sender {

}
- (void)handleSpchatTapview:(UITapGestureRecognizer *)sender {

}
#pragma mark - 屏幕方向改变
- (BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return  UIInterfaceOrientationPortrait;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark - analyticsEvent
- (void)analyticsEvent1 {
    [MobClick event:@"xl_message" attributes:@{@"userid" : [[XLAccountManager shareInstance] model].Id ?: @""}];
    [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_message" action:@"xl_message" userId:[[XLAccountManager shareInstance] model].Id camgirlId:nil] subscribeNext:^(id x) {
    } error:^(NSError *error) {
    }];
}
#pragma mark - 检测相机的权限是否开启
- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        //[self analyticsEvent14];
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}
@end
